import {useState} from "react";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import * as z from "zod";
import {format} from "date-fns";
import {Form, FormControl, FormField, FormItem, FormLabel, FormMessage,} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select";
import {Calendar} from "@/components/ui/calendar";
import {Popover, PopoverContent, PopoverTrigger,} from "@/components/ui/popover";
import {cn} from "@/lib/utils";
import {CalendarIcon} from "lucide-react";

import api from "@/config/http";

import {userFormSchema} from './UserFormSchema'
import {User} from "@/types/User";
import {Gender, UserRole} from "@/types/Enums";

// Define the form schema using Zod


// Define form values type
type FormValues = z.infer<typeof userFormSchema>;

interface CreateUserFormProps {
    onSuccess: () => void;
    onCancel: () => void;

    user:User| null
}

 export const CreateUserForm = ({ onSuccess, onCancel,user }: CreateUserFormProps) => {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [previewAvatar, setPreviewAvatar] = useState<string | null>(null);
    const [previewImages, setPreviewImages] = useState<string[]>([]);
    const [previewVideo, setPreviewVideo] = useState<string | null>(null);

    const form = useForm<FormValues>({
        resolver: zodResolver(userFormSchema),
        defaultValues:user?{...user}: {
            name:'',
            phone: "",
            address: "",
            wechat: "",
            gender: Gender.Male,
            role: UserRole.User,
            otherImages: [],
        },
    });

    const onSubmit = async (values: FormValues) => {
        setIsSubmitting(true);
        try {
            const formData = new FormData();
            formData.append("phone", values.phone);
            formData.append("address", values.address);
            formData.append("dateOfBirth", values.birthDate.toISOString());
            formData.append("wechat", values.wechat);
            formData.append("gender", values.gender);
            formData.append("role", values.role);
            formData.append("avatar", values.avatar);
            values.otherImages?.forEach((image: File, index: number) => {
                formData.append(`otherImages[${index}]`, image);
            });
            formData.append("selfieVideo", values.selfieVideo);

            // Replace with your API endpoint
            await api.post("/api/users", formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            });

            form.reset();
            setPreviewAvatar(null);
            setPreviewImages([]);
            setPreviewVideo(null);
            onSuccess();
            alert("用户创建成功");
        } catch (error) {
            console.error("创建用户失败:", error);
            alert("创建用户失败，请稍后重试");
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            form.setValue("avatar", file);
            setPreviewAvatar(URL.createObjectURL(file));
        }
    };

    const handleImagesChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = Array.from(e.target.files || []);
        form.setValue("otherImages", files);
        const previews = files.map((file) => URL.createObjectURL(file));
        setPreviewImages(previews);
    };

    const handleVideoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            form.setValue("selfieVideo", file);
            setPreviewVideo(URL.createObjectURL(file));
        }
    };

    return (
        <div className="max-w-2xl mx-auto p-6">
            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">

                    <FormField
                        control={form.control}
                        name="name"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>姓名</FormLabel>
                                <FormControl>
                                    <Input placeholder="姓名" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="phone"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>手机号码</FormLabel>
                                <FormControl>
                                    <Input placeholder="+8612345678900" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="address"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>地址</FormLabel>
                                <FormControl>
                                    <Input placeholder="请输入详细地址" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="birthDate"
                        render={({ field }) => (
                            <FormItem className="flex flex-col">
                                <FormLabel>出生日期</FormLabel>
                                <Popover>
                                    <PopoverTrigger asChild>
                                        <FormControl>
                                            <Button
                                                variant="outline"
                                                className={cn(
                                                    "w-[240px] pl-3 text-left font-normal",
                                                    !field.value && "text-muted-foreground"
                                                )}
                                            >
                                                {field.value ? (
                                                    format(field.value, "PPP")
                                                ) : (
                                                    <span>选择日期</span>
                                                )}
                                                <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                                            </Button>
                                        </FormControl>
                                    </PopoverTrigger>
                                    <PopoverContent className="w-auto p-0" align="start">
                                        <Calendar
                                            mode="single"
                                            selected={field.value}
                                            onSelect={field.onChange}
                                            disabled={(date) =>
                                                date > new Date() || date < new Date("1900-01-01")
                                            }
                                            autoFocus
                                        />
                                    </PopoverContent>
                                </Popover>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="wechat"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>微信号</FormLabel>
                                <FormControl>
                                    <Input placeholder="请输入微信号" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="gender"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>性别</FormLabel>
                                <Select onValueChange={field.onChange} defaultValue={field.value}>
                                    <FormControl>
                                        <SelectTrigger>
                                            <SelectValue placeholder="选择性别" />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        <SelectItem value="male">男</SelectItem>
                                        <SelectItem value="female">女</SelectItem>
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="role"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>角色</FormLabel>
                                <Select onValueChange={field.onChange} defaultValue={field.value}>
                                    <FormControl>
                                        <SelectTrigger>
                                            <SelectValue placeholder="选择角色" />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        <SelectItem value="user">用户</SelectItem>
                                        <SelectItem value="admin">管理员</SelectItem>
                                        <SelectItem value="moderator">版主</SelectItem>
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="avatar"
                        render={() => (
                            <FormItem>
                                <FormLabel>头像</FormLabel>
                                <FormControl>
                                    <div className="flex items-center space-x-4">
                                        <Input
                                            type="file"
                                            accept="image/jpeg,image/png"
                                            onChange={handleAvatarChange}
                                        />
                                        {previewAvatar && (
                                            <img
                                                src={previewAvatar}
                                                alt="Avatar preview"
                                                className="h-20 w-20 object-cover rounded-full"
                                            />
                                        )}
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="otherImages"
                        render={() => (
                            <FormItem>
                                <FormLabel>其他图片</FormLabel>
                                <FormControl>
                                    <div className="flex items-center space-x-4">
                                        <Input
                                            type="file"
                                            accept="image/jpeg,image/png"
                                            multiple
                                            onChange={handleImagesChange}
                                        />
                                        <div className="flex space-x-2">
                                            {previewImages.map((src, index) => (
                                                <img
                                                    key={index}
                                                    src={src}
                                                    alt={`Image preview ${index + 1}`}
                                                    className="h-20 w-20 object-cover rounded"
                                                />
                                            ))}
                                        </div>
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="selfieVideo"
                        render={() => (
                            <FormItem>
                                <FormLabel>自拍视频</FormLabel>
                                <FormControl>
                                    <div className="flex items-center space-x-4">
                                        <Input
                                            type="file"
                                            accept="video/mp4,video/webm"
                                            onChange={handleVideoChange}
                                        />
                                        {previewVideo && (
                                            <video
                                                src={previewVideo}
                                                controls
                                                className="h-20 w-32 object-cover rounded"
                                            />
                                        )}
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <Button type="submit" disabled={isSubmitting}>
                        {isSubmitting ? "提交中..." : "创建用户"}
                    </Button>
                </form>
            </Form>
        </div>
    );
};

